import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.jchy.photo.Date;
import com.jchy.photo.Person;
//import java.awt.image.BufferedImage;
//import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.File;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import java.io.FileNotFoundException;
//import javax.imageio.ImageIO;

public class StaticPhotoBuilder {

	public static final long serialVersionUID=999;
	
    String initpath;
    String title;
    ResourceBundle rb;
    boolean showQuery;
    //PrintWriter out;

    int columns;
    int rows;
    String sessionid;
    int i;
    boolean FindNew;
    boolean NoItems;
    
    String connection;
    String start, thumbs, oversize;
    /* double thumbsize; */

    String /* maxresults, */ imgmain, imgthmb;
    String imgover /*, printsize, printrows */;
    /* String printwide, printurl, printdir; */
    /* String iuimages, iuthumbs; */
    boolean maintpeople, maintthings, maintplaces; 
    boolean maintdates, updatebtn, updatethumb;
    boolean additems, canfindnew;

    String root;
    
    public ResultSet executeQuery (String query)
       throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException 
    {
        ResultSet rs=null;
            Class.forName("org.gjt.mm.mysql.Driver").newInstance();
            java.sql.Connection conn;
            conn = DriverManager.getConnection(connection);
            Statement stmt;

            stmt=conn.createStatement();
                  
            rs = stmt.executeQuery(query);

            conn.close();
 

        return rs;
    }

    public void init()
    {
        root = "c:\\photoportable\\";
    	rb = ResourceBundle.getBundle("Environment");
        showQuery = false; /* rb.getString("servletAlbum.showQuery").equals("yes"); */
        connection = rb.getString("servletAlbum.connection");
        start = rb.getString("servletAlbum.start");
        thumbs = rb.getString("servletAlbum.thumbs");
        oversize = rb.getString("servletAlbum.oversize");
        /* thumbsize = Double.parseDouble(rb.getString("servletAlbum.thumbsize")); */
        /* maxresults = rb.getString("servletAlbum.maxresults"); */
        imgmain = "../../images/";
        imgthmb = "thumbs/";
        imgover = "../../oversize/";
/*        printsize = rb.getString("servletAlbum.printsize");
        printrows = rb.getString("servletAlbum.printrows");
        printwide = rb.getString("servletAlbum.printwide");
        printurl = rb.getString("servletAlbum.printurl");
        printdir = rb.getString("servletAlbum.printdir");
        oversize = rb.getString("imgupdate.oversize");
        iuimages = rb.getString("imgupdate.images");
        iuthumbs = rb.getString("imgupdate.thumbs"); */
        title = "Photo Album";
        maintpeople = false;
        maintthings = false;
        maintplaces = false;
        maintdates = false;
        updatebtn = false;
        updatethumb = false;
        additems = false;
        canfindnew = false;
        columns=8;
        rows=6;
        
    }
	

    public boolean writeIndexHtml(String sessionid,
    		              int page,
    		              PrintWriter pwout) 
       throws FileNotFoundException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, IOException
    {

        ResultSet rs;
        boolean hasMorePages=false;
    	PrintWriter imageOut;
        
        int begin;
        int end;

        begin=(page-1)*rows*columns + 1;
        end=page*rows*columns;

        pwout.println("<html>");
        pwout.println("<body bgcolor=\"white\">");
        pwout.println("<head>");
        pwout.println("<title>Search Results " + String.valueOf(page) + "</title>");  
        pwout.println("</head>");
        pwout.println("<body>");
        
        if(showQuery)
        	pwout.println(connection);
        
        if(showQuery) 
        	pwout.println("Session ID = "+sessionid);
        
        String getSession = "SELECT image_file, date " +
                            "FROM session_results "+
                            "WHERE session_uid = " + sessionid + " " +
                            "ORDER BY (date) DESC, (image_file) DESC;";
        if(showQuery)
            pwout.println("Get Session: "+getSession+"<BR>");

        rs = executeQuery(getSession);

        pwout.println("<TABLE>");
        i=1;
        while(rs.next()) 
        {
            if(i>=begin && i<=end)
            {
                String image_file = rs.getString("image_file");

                File srcFile;
                File tgtFile; 
                tgtFile = new File(root + "thumbs\\");
                if(!tgtFile.exists()) {
                	tgtFile.mkdir();
                }
                
                srcFile = new File(thumbs + File.separator + image_file);
                tgtFile = new File(root + "thumbs\\" + image_file);
                copyFile(srcFile,tgtFile);
                
                tgtFile = new File(root + "pages\\");
                if(!tgtFile.exists()) {
                	tgtFile.mkdir();
                }

                tgtFile = new File(root + "pages\\images\\");
                if(!tgtFile.exists()) {
                	tgtFile.mkdir();
                }

                imageOut = new PrintWriter(new FileOutputStream(root + "pages\\images\\image_" + image_file.replace(".","_") + ".html"));
				writeImageHtml(image_file, page, sessionid, imageOut);
				imageOut.close();
                
                String date = rs.getString("date");
                if(i%columns==1) pwout.println("<TR>");
                pwout.println("<TD>");
                pwout.println("<A HREF=\"pages\\images\\image_" + image_file.replace(".","_") + ".html\">");
                pwout.print("<IMAGE SRC=\"" + imgthmb + "/" + image_file +"\" ");
                pwout.print("VSPACE=\"0\" HSPACE=\"0\" BORDER=\"0\"");
                pwout.println(">");
                pwout.println("</A><BR>");
                pwout.println(Date.MonthDayYear(date));
                pwout.println("</TD>"); 
                if(i%columns==0) pwout.println("</TR>");
            }
            i++;
        }
        pwout.println("</TABLE><BR>");
        pwout.println((i-1)+" image(s) found.<BR>");
        pwout.print("Displaying "+begin+" through ");
        if(end>(i-1))
            pwout.print(String.valueOf(i-1)+"<BR>");
        else
            pwout.print(String.valueOf(end));
        pwout.println("<BR>");
        pwout.println("<TABLE BORDER=0><TR>");
        if(page>1)
        {
            pwout.println("<TD>");
            if(page==2)
            	pwout.println("<A HREF=\"index.html\">Prev</A>");
            else
            	pwout.println("<A HREF=\"index" + String.valueOf(page-1) + ".html\">Prev</A>");
            pwout.println("</TD>");
        }
        if(end<(i-1))
        {
        	hasMorePages = true;
        	pwout.println("<TD>");
        	pwout.println("<A HREF=\"index" + String.valueOf(page+1) + ".html\">Next</A>");
        	pwout.println("</TD>");
        }

        pwout.println("<TD>&nbsp;</TD>");
        pwout.println("</TR></TABLE>");
        pwout.println("</body>");
        pwout.println("</html>");
        
        return hasMorePages;
        
    }

    
    public void writeImageHtml(String image, int page, String sess, PrintWriter pwout)
    throws SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, IOException {
    	
    	PrintWriter oversizeOut;

    	pwout.println("<html>");
		pwout.println("<body bgcolor=\"white\">");
		pwout.println("<head>");
		
		pwout.println("<title>Image " + image + "</title>");  
		pwout.println("</head>");
		pwout.println("<body>");
		
		pwout.println("<TABLE BORDER=1><TR><TD VALIGN=TOP>");
		pwout.println("</TD>");
		
		  String query;
		  ResultSet rs;
		  String image_uid="";
		  String description = "";
		  int count=0;
		
		  // Get image_uid
		  query = "SELECT images.uid, images.description FROM images " +
		          "WHERE TRIM(images.image_file) = \"" + image + "\"";
		  if(showQuery) pwout.println("Query: " + query + "<BR>");
		  rs = executeQuery(query);
		  while(rs.next())
		  {
		  	image_uid = rs.getString("images.uid"); 
			description = rs.getString("images.description"); 
		  } 
		
		  query = "SELECT session_uid, image_file " +
		          "FROM session_results " +
		          "WHERE session_uid = " + sess + " " +
		          "ORDER BY (date) DESC, (image_file) DESC;";
		  if(showQuery) pwout.println("Get session: " + query + "<BR>");
		  rs = executeQuery(query);
		  while(rs.next())
		  {
		      if(rs.getString("image_file").equals(image) && !rs.isFirst())
		      {
		          rs.previous();
		          String prev=rs.getString("image_file");
		          pwout.println("<TD VALIGN=TOP>");
		          pwout.println("<A HREF=\"image_" + prev.replace(".", "_") + ".html\">Prev</A>");
		          pwout.println("</TD>");
		          rs.next();
		      }
		      if(rs.getString("image_file").equals(image) && !rs.isAfterLast() && !rs.isLast())
		      {
		          rs.next();
		          String next=rs.getString("image_file");
		          pwout.println("<TD VALIGN=TOP>");
		          pwout.println("<A HREF=\"image_" + next.replace(".", "_") + ".html\">Next</A>");
		          pwout.println("</TD>");
		      }
		  }
		          
		  pwout.println("<TD VALIGN=TOP>");
		  if(page==1)
			  pwout.println("<A HREF=\"../../index.html\">Search Results</A>");
		  else
			  pwout.println("<A HREF=\"../../index" + String.valueOf(page) + ".html\">Search Results</A>");
		  pwout.println("</TD>");
		
		  String oversizeFileName = oversize+File.separator+image;
		  if(showQuery)
		     pwout.println("Oversize File: " + oversizeFileName);
		  File oversizeFile = new File(oversizeFileName);
		  if(showQuery) 
		     pwout.println("Oversize File Exists: "+String.valueOf(oversizeFile.exists()));
		  if(oversizeFile.exists())
		  {
//		      BufferedImage bufi = ImageIO.read(oversizeFile);
//		      String oversizeDim=String.valueOf(bufi.getWidth())+" X "+String.valueOf(bufi.getHeight());
		    
            File tgtFile;
			tgtFile = new File(root + "pages\\");
            if(!tgtFile.exists()) {
            	tgtFile.mkdir();
            }
			tgtFile = new File(root + "pages\\oversize\\");
            if(!tgtFile.exists()) {
            	tgtFile.mkdir();
            }

			oversizeOut = new PrintWriter(new FileOutputStream(root + "pages\\oversize\\oversize_" + image.replace(".","_") + ".html"));
			writeOversizeHtml(image, oversizeOut);
			oversizeOut.close();
                
			pwout.println("<TD VALIGN=TOP>");
			pwout.println("<A HREF=\"../oversize/oversize_" + image.replace(".", "_") + ".html\" target=\"oversize\">Full Size</A>");
		  	pwout.println("</TD>");
		  }
		  pwout.println("</TR></TABLE>");
		  pwout.println("<TABLE><TR><TD VALIGN=TOP>");
		
		  // Begin Dates
		  query = "SELECT COUNT(*) FROM image_date WHERE image_date.image_uid = " + image_uid;
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  rs.next();
		  count = rs.getInt("count(*)");
		
		  query = "SELECT dates.uid, dates.date, image_date.image_uid " +
		          "FROM dates " +
		          "LEFT OUTER JOIN image_date " +
		          "ON dates.uid = image_date.date_uid " +
		          "AND image_date.image_uid = " + image_uid + " " +
		          "ORDER BY dates.date DESC";
		  rs = executeQuery(query);
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		  pwout.println("<B>Dates</B><BR>");
		  pwout.println("<TABLE>");
		
		  if(count==0)
		      pwout.println("<TR><TD>None</TD></TR>");
		
		  while (rs.next()) 
		  {
		      String date = rs.getString("dates.date");   
		      String outer = rs.getString("image_date.image_uid"); 
		      if(outer!=null)
		          pwout.println("<TR><TD>"+Date.MonthDayYear(date)+"</TD></TR>");
		  }
		  pwout.println("</TABLE>");
		  // End Dates
		
		  pwout.println("</TD><TD VALIGN=TOP>");
		
		  // Begin People
		  query = "SELECT COUNT(*) FROM image_person WHERE image_person.image_uid = " + image_uid;
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  rs.next();
		  count = rs.getInt("count(*)");
		
		  query = "SELECT people.*," +
		          " image_person.image_uid " +
		          "FROM people " +
		          "LEFT OUTER JOIN image_person " +
		          "ON people.uid = image_person.person_uid " +
		          "AND image_person.image_uid = " + image_uid + " " +
		          "ORDER BY people.lastName, people.firstName, people.middleName";
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  pwout.println("<B>People</B><BR>");
		  pwout.println("<TABLE>");
		
		  if(count==0)
		      pwout.println("<TR><TD>None</TD></TR>");
		
		  while (rs.next()) 
		  {
		      String name=Person.FirstNameLastName(rs);
		      String outer = rs.getString("image_person.image_uid"); 
		      if(outer!=null)
		          pwout.println("<TR><TD>" + name + "</TD></TR>");
		  }
		  pwout.println("</TR></TABLE>");
		  // End People
		
		  pwout.println("</TD><TD VALIGN=TOP>");
		
		  // Begin Things
		  query = "SELECT COUNT(*) FROM image_thing WHERE image_thing.image_uid = " + image_uid;
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  rs.next();
		  count = rs.getInt("count(*)");
		
		  query = "SELECT things.uid, things.thing, " +
		          " image_thing.image_uid " +
		          "FROM things " +
		          "LEFT OUTER JOIN image_thing " +
		          "ON things.uid = image_thing.thing_uid " +
		          "AND image_thing.image_uid = " + image_uid + " " +
		          "ORDER BY things.thing";
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  pwout.println("<B>Things</B><BR>");
		  pwout.println("<TABLE>");
		
		  if(count==0)
		      pwout.println("<TR><TD>None</TD></TR>");
		
		  while (rs.next()) 
		  {
		      String thing = rs.getString("things.thing");    
		      String outer = rs.getString("image_thing.image_uid"); 
		      if(outer!=null)
		          pwout.println("<TR><TD>" + thing + "</TD></TR>");
		  }
		  pwout.println("</TABLE>");
		  // End Things
		
		  pwout.println("</TD><TD VALIGN=TOP>");
		
		  // Begin Places
		  query = "SELECT COUNT(*) FROM image_place WHERE image_place.image_uid = " + image_uid;
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  rs.next();
		  count = rs.getInt("count(*)");
		
		  query = "SELECT places.uid, places.place, " +
		          " image_place.image_uid " +
		          "FROM places " +
		          "LEFT OUTER JOIN image_place " +
		          "ON places.uid = image_place.place_uid " +
		          "AND image_place.image_uid = " + image_uid + " " +
		          "ORDER BY places.place";
		  
		  if(showQuery)
		      pwout.println("Query:<BR>" + query + "<BR>");
		
		  rs = executeQuery(query);
		
		  pwout.println("<B>Places</B><BR>");
		  pwout.println("<TABLE>");
		
		  if(count==0)
		      pwout.println("<TR><TD>None</TD></TR>");
		
		  while (rs.next()) 
		  {
		      String place = rs.getString("places.place");    
		      String outer = rs.getString("image_place.image_uid"); 
		      if(outer!=null)
		           pwout.println("<TR><TD>" + place + "</TD></TR>");
		  }
		  pwout.println("</TABLE>");
		  // End Places
		
		  pwout.println("</TD></TR></TABLE>");
		  pwout.println("</FORM>");

          File srcFile;
          File tgtFile; 
          tgtFile = new File(root + "images\\");
          if(!tgtFile.exists()) {
          	tgtFile.mkdir();
          }
          
          srcFile = new File(start + File.separator + image);
          tgtFile = new File(root + "images\\" + image);
          copyFile(srcFile,tgtFile);
		  
		  
		  pwout.println("<BR>");
		  pwout.println("<TABLE>");
		  pwout.println("<TR><TD><IMAGE SRC=\"" + imgmain + "/" + image + "\"></TD></TR>");
		  pwout.println("<TR><TD>" + description + "</TD></TR>");
		  pwout.println("</TABLE>");
		
		pwout.println("</body>");
		pwout.println("</html>");
		
	}

    public void writeOversizeHtml(String image, PrintWriter pwout)
    throws SQLException, IllegalAccessException, InstantiationException, ClassNotFoundException, IOException {
        pwout.println("<html>");
        pwout.println("<body bgcolor=\"white\">");
        pwout.println("<head>");

        pwout.println("<title>Oversize " + image + "</title>");  
        pwout.println("</head>");
        pwout.println("<body>");

        File srcFile;
        File tgtFile; 
        tgtFile = new File(root + "oversize\\");
        if(!tgtFile.exists()) {
        	tgtFile.mkdir();
        }
        
        srcFile = new File(oversize + File.separator + image);
        tgtFile = new File(root + "oversize\\" + image);
        if(srcFile.exists())
        	copyFile(srcFile,tgtFile);

        pwout.print("<img src=\"" + imgover + "/" + image + "\">");
        pwout.println("<BR>");

        pwout.println("</body>");
        pwout.println("</html>");
    	
    }
    
    /**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		StaticPhotoBuilder spb = new StaticPhotoBuilder();
		try {
			spb.init();
			boolean hasMorePages = false;
			int page = 1;
			String session = "4696";
			PrintWriter writer = new PrintWriter(new FileOutputStream(spb.root + "index.html"));
			hasMorePages = spb.writeIndexHtml(session, page, writer);
			writer.close();
			while(hasMorePages) {
				page++;
				writer = new PrintWriter(new FileOutputStream(spb.root + "\\index" + String.valueOf(page) + ".html"));
				hasMorePages = spb.writeIndexHtml(session, page, writer);
				writer.close();
			}
			
		}
		catch(FileNotFoundException fnfe) {
			System.out.println("FileNotFoundException: " + fnfe);
		}
        catch(ClassNotFoundException cnfe)
        {
            System.out.println("Class Not Found Exception "+cnfe.toString());
        }
        catch(InstantiationException ie)
        {
            System.out.println("Instantiation Exception "+ie.toString());
        }        
        catch(IllegalAccessException iae)
        {
            System.out.println("Illegal Access Exception "+iae.toString());
        }
        catch(SQLException sqle)
        {
            System.out.println("SQL Exception "+sqle.toString());
        }
        catch(IOException ioe)
        {
            System.out.println("Input/Output Exception "+ioe.toString());
        }
		
	}

	public void copyFile(File in, File out) throws FileNotFoundException, IOException {
		    FileInputStream fis  = new FileInputStream(in);
		    FileOutputStream fos = new FileOutputStream(out);
		    byte[] buf = new byte[1024];
		    int i = 0;
		    while((i=fis.read(buf))!=-1) {
		      fos.write(buf, 0, i);
		      }
		    fis.close();
		    fos.close();
    }
}
